package ua.kharkov.knure.mikhaylov.st4.web.command;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.knure.mikhaylov.st4.db.entities.User;
import ua.kharkov.knure.mikhaylov.st4.db.management.DBManager;
import ua.kharkov.knure.mikhaylov.st4.settings.LocaleData;
import ua.kharkov.knure.mikhaylov.st4.settings.Path;

/**
 * Command - updates user settings
 * 
 * @author Saint
 * 
 */
public class UpdateSettingsCommand extends Command {

	private static final long serialVersionUID = 4412239013076624835L;
	private static final Logger log = Logger
			.getLogger(UpdateSettingsCommand.class);

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		log.debug("Command starts");

		log.trace("Checking updated parameters");

		HttpSession session = request.getSession();

		String firstName = request.getParameter("firstName");
		String lastName = request.getParameter("lastName");

		User user = (User) session.getAttribute("user");

		// error handler
		String errorMessage = null;
		String forward = Path.PAGE_ERROR;

		if (firstName == null || lastName == null || firstName.isEmpty()
				|| lastName.isEmpty()) {
			errorMessage = LocaleData.getResourceBundle().getString(
					"servlet.error.names.null");
			request.setAttribute("errorMessage", errorMessage);
			log.error("errorMessage --> " + errorMessage);
			return forward;
		}

		if (user.getFirstName().equals(firstName)
				&& user.getLastName().equals(lastName)) {
			errorMessage = LocaleData.getResourceBundle().getString(
					"servlet.error.userdata");
			request.setAttribute("errorMessage", errorMessage);
			log.error("errorMessage --> " + errorMessage);
			return forward;
		} else {
			user.setFirstName(firstName);
			user.setLastName(lastName);

			log.trace("Got user first name --> " + firstName);
			log.trace("Got user last name --> " + lastName);

			log.trace("User data updated");

			DBManager.getInstance().updateUser(user);
			log.trace("User data updated in db");

			session.setAttribute("user", user);
			log.trace("Set the session attribute: user --> " + user);

			request.setAttribute("message", LocaleData.getResourceBundle()
					.getString("servlet.success.settings.update"));
			request.setAttribute("next", Path.COMMAND_BROWSE_SETTINGS);

			forward = Path.PAGE_SUCCESS;
		}

		log.debug("Command finished");
		return forward;
	}

}
